package com.xinwangai.jingbai.service.impl;

import com.xinwangai.jingbai.mapper.UserMapper;
import com.xinwangai.jingbai.pojo.BO.UserBO;
import com.xinwangai.jingbai.pojo.DTO.UserDTO;
import com.xinwangai.jingbai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 用户服务实现类
 *
 * @author guo.wenliang
 * @since 2025/1/15
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    /**
     * 简单的MD5密码加密
     */
    private String encryptPassword(String password) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] bytes = md.digest(password.getBytes());
            StringBuilder sb = new StringBuilder();
            for (byte b : bytes) {
                sb.append(String.format("%02x", b));
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return password; // 如果加密失败，返回原密码
        }
    }

    @Override
    public Long addUser(UserDTO userDTO) {
        try {
            // 检查用户名是否已存在
            UserBO existingUser = userMapper.getUserByUsername(userDTO.getUsername());
            if (existingUser != null) {
                throw new RuntimeException("用户名已存在");
            }
            
            // 检查邮箱是否已存在
            if (userDTO.getEmail() != null && !userDTO.getEmail().isEmpty()) {
                UserBO existingEmail = userMapper.getUserByEmail(userDTO.getEmail());
                if (existingEmail != null) {
                    throw new RuntimeException("邮箱已存在");
                }
            }
            
            // 加密密码
            if (userDTO.getPassword() != null && !userDTO.getPassword().isEmpty()) {
                userDTO.setPassword(encryptPassword(userDTO.getPassword()));
            }
            
            // 设置默认状态
            if (userDTO.getStatus() == null) {
                userDTO.setStatus(1); // 默认启用
            }
            
            int result = userMapper.addUser(userDTO);
            if (result > 0) {
                return userDTO.getId(); // 返回生成的用户ID
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("添加用户失败：" + e.getMessage());
        }
    }

    @Override
    public boolean updateUser(UserDTO userDTO) {
        try {
            // 如果更新密码，需要加密
            if (userDTO.getPassword() != null && !userDTO.getPassword().isEmpty()) {
                userDTO.setPassword(encryptPassword(userDTO.getPassword()));
            }
            
            int result = userMapper.updateUser(userDTO);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public boolean deleteUser(Long id) {
        try {
            int result = userMapper.deleteUser(id);
            return result > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public UserBO getUserById(Long id) {
        try {
            return userMapper.getUserById(id);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public UserBO getUserByUsername(String username) {
        try {
            return userMapper.getUserByUsername(username);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public UserBO getUserByEmail(String email) {
        try {
            return userMapper.getUserByEmail(email);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
